﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using static Dapper.SqlMapper;

namespace Trade.Journal
{
    public class BarCycleTypeHandler : ITypeHandler
    {
        public object Parse(Type destinationType, object value)
        {
            return BarCycle.FromString(value.ToString());
        }

        public void SetValue(IDbDataParameter parameter, object value)
        {
            if (value is BarCycle cycle)
                parameter.Value = cycle.ToString();
        }
    }

    public class VersonTypeHandler : ITypeHandler
    {
        public object Parse(Type destinationType, object value)
        {
            return Version.Parse(value.ToString());
        }

        public void SetValue(IDbDataParameter parameter, object value)
        {
            if (value is Version v)
            parameter.Value = v.ToString();
        }
    }


    public class BitmapSourceTypeHandler : ITypeHandler
    {
        public object Parse(Type destinationType, object value)
        {
            if (value is byte[] data)
            {
                var bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(data);
                bmp.EndInit();
                return bmp;
            }
            else return value;
        }

        public void SetValue(IDbDataParameter parameter, object value)
        {
            if (value is BitmapSource source)
            {
                BitmapFrame frame = BitmapFrame.Create(source);
                var png = new JpegBitmapEncoder();
                png.Frames.Add(frame);

                using MemoryStream ms = new MemoryStream();

                png.Save(ms);
                ms.Position = 0;

                var by = ms.ToArray();
                parameter.Value = by;
            }
        }
    }


    public class OpportunityTypeHandler : ITypeHandler
    {
        public object Parse(Type destinationType, object value)
        {
            if (value is string data) 
                return Opportunity.Parse(data);  
            else return value;
        }

        public void SetValue(IDbDataParameter parameter, object value)
        {
            parameter.Value = value.ToString();
        }
    }

}
